package com.it.myd.websocket.socket.match;

import com.it.myd.bean.main.ReturnValue;
import com.it.myd.controller.main.module.WuZiQiController;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class JoinMatchWebSocket extends TextWebSocketHandler {

    @Autowired
    WuZiQiController wuZiQiController;

    private Map<WebSocketSession,Map<String,String>> userMap = new HashMap<>();
    private Map<String, List<WebSocketSession>> sessionMap = new HashMap<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        //在websocket连接建立成功后，被自动调用
        System.out.println("TestWebSocket连接成功");
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String json = message.getPayload();
        JSONObject jsonObject = new JSONObject(json);
        String userid =jsonObject.getString("userid");
        String state =jsonObject.getString("state");
        String type =jsonObject.getString("type");
        ReturnValue returnValue = wuZiQiController.joinMatcher(userid,type,state,session);
        TextMessage m = new TextMessage(returnValue.toJson());
        Map<String,String> map = new HashMap<>();
        map.put("userid",userid);
        map.put("type",type);
        userMap.put(session,map);
        session.sendMessage(m);
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        //连接出现异常的时候，被自动调用
        System.out.println("TestWebSocket连接异常");
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        Map<String,String> map = userMap.remove(session);
        if(map != null){
            String userid = map.get("userid");
            String type = map.get("type");
            wuZiQiController.joinMatcher(userid,type,"-2",session);
        }
        System.out.println("TestWebSocket关闭连接");
    }

}
